package com.SMS;



import java.util.ArrayList;



import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMSActivity extends Activity {
	
	     Button btnSendSMS;
	     EditText txtPhoneNo;
	     EditText txtMessage;
	    public StringBuilder sb = new StringBuilder();
	    private static final String DEBUG_TAG = null;
	    private Context context = this;
		
		
		
		
		/** Called when the activity is first created. */
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        //--------------------------------getting Phone contact-----------------------------
	        
	        Cursor cursor = null;
	        
	        try {
	              Uri result=getIntent().getData();
	            Log.v(DEBUG_TAG, "Got a contact result: "
	                    + result.toString());

	      

	            // query for getting Contact details
	             cursor = managedQuery(result,
	                    null, null, null, null);
	           
	            if (cursor.moveToFirst()) {
	            	String id1 = cursor.getString(
	                        cursor.getColumnIndex(ContactsContract.Contacts._ID));
	    	      String name = cursor.getString(
	                        cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
	    	      sb.append("Name : ");
	    	       sb.append(name);
	    	       sb.append("\n");
	    	       String hasPhoneNumber = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
	    	       if (Integer.parseInt(hasPhoneNumber) > 0) {
	                     
	                    
	                    Uri myPhoneUri = Uri.withAppendedPath(
	                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id1);
	                     
	                    
	                    cursor = getContentResolver().query(Phone.CONTENT_URI,
	                            null, Phone.CONTACT_ID + "=?", new String[] { id1 },
	                            null);

	                    int PhoneIdx = cursor.getColumnIndex(Phone.DATA);
	                  
	                    // Get the phone numbers from the contact
	                    if (cursor.moveToFirst()) {
	                         
	                        // Get a phone number
	                        String phoneNumber =cursor.getString(PhoneIdx);
	                        sb.append("PhoneNumber : ");
	                        sb.append(phoneNumber);
	                        sb.append("\n");
	                        
	                    }
	                } else {
	                	Toast.makeText(this, "This contact doesn't have a phone number",
	                            Toast.LENGTH_LONG).show();
	                	
	                }


	                Log.v(DEBUG_TAG, "Got data: " + name);
	            } else {
	                Log.w(DEBUG_TAG, "No results");
	            }
	        } catch (Exception e) {
	            Log.e(DEBUG_TAG, "Failed to get  data", e);
	        } finally {
	            if (cursor != null) {
	                cursor.close();
	            }
	            EditText Entry = (EditText) findViewById(R.id.txtMessage);
	            Entry.setText(sb.toString());
	           
	            

	        }

	        
	            
	        
	        
	        
	        
	        //----------------------------------------------------------------------------------
	        //To get phone number
	        
	        ArrayList<String> phonelist=getphonelist();
	        
	        if(phonelist.isEmpty())
	        {
	        	
	        }
	        else
	        {
	        
	        AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtPhoneNo);
	        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, phonelist);
	        textView.setAdapter(adapter);
	        }
	        
	        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
	        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
	        txtMessage = (EditText) findViewById(R.id.txtMessage);
	        btnSendSMS.setOnClickListener(new View.OnClickListener() 
	        {
	            public void onClick(View v) 
	            {                
	                String phoneNo = txtPhoneNo.getText().toString();
	                String message = txtMessage.getText().toString();                 
	                if (phoneNo.length()>0 && message.length()>0)                
	                    sendSMS(phoneNo, message);                
	                else
	                    Toast.makeText(getBaseContext(), 
	                        "Please enter both phone number and message.", 
	                        Toast.LENGTH_SHORT).show();
	            }
	        });   
	    }
	    
		
    
    //Function to get Phone list
    public ArrayList<String> getphonelist()
    {
    	Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,    null, null, null, null);
        
        ArrayList<String> phonelist = new ArrayList<String>();
        if (cur.getCount() > 0) {
        
        	while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String hasPhoneNumber = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
		       if (Integer.parseInt(hasPhoneNumber) > 0) {
                  
                
                 
                  
                 // Query the table
                 Cursor phoneCursor = getContentResolver().query(Phone.CONTENT_URI,
                         null, Phone.CONTACT_ID + "=?", new String[] { id },
                         null);
                 while(phoneCursor.moveToNext())
                 {
                	 String phoneNumber = phoneCursor.getString(phoneCursor
                             .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        phonelist.add(phoneNumber);       
                 }
		       }
            }
        }
        return phonelist;
    }
    
    
    
    
    //Function for sending SMS
            
    private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
 
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
 
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
           
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        
 
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);  
    //to store details in database
        datastore db=new datastore(context);
		db.openDB();
		db.Insert(phoneNumber,message);
		db.close();
    }
}